package com.mediacloud.app.newsmodule.activity;

import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chinamcloud.collect.AcquisitionManager;
import com.chinamcloud.report.ReportKit;
import com.eventTrack.TXReportManager;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.IntegralConfig;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.utils.NeedTokenType;
import com.mediacloud.app.model.utils.SDKNewsItemJump;
import com.mediacloud.app.model.utils.WebViewUtils;
import com.mediacloud.app.model.view.WebBrowser;
import com.mediacloud.app.model.view.WebBrowserX;
import com.mediacloud.app.nav2.utils.DateUtils;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.MemberApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi;
import com.mediacloud.app.newsmodule.fragment.webview.WebViewFragment;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.WebViewLinkCMSNewsHandle;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.ServerAppConfigInfo.NavigateBarStyle;
import com.mediacloud.app.reslib.enums.TitileType;
import com.mediacloud.app.reslib.util.HomeTab;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.user.utils.RxUtils;
import com.mediacloud.app.util.IOSTips;
import com.mediacloud.app.util.OfflineWebUtil;
import com.tencent.mmkv.MMKV;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.URLUtil;
import com.tencent.smtt.sdk.WebView;
import com.utils.UriTool;
import com.zimeiti.details.MediaAuthorDetailActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.MD5;

import java.net.URLDecoder;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.HttpUrl;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.Url;

/**
 * 网页链接
 */
@SuppressWarnings("ALL")
public class WebViewPageActivity extends StyleSetActivity {


    static CatalogItem catalogItem2;
    WebViewFragment fragment;
    public TopbackHandle topbackHandle;
    protected int tokenTag = NeedTokenType.Delayed;
    protected NewsDetailInvoker newsDetailInvoker;
    protected DetialCallBack detialCallBack;
    protected int linkType = 0;
    String argUrl;
    String newsType;
    boolean isGlobal24 = false;
    private static boolean fromUserCenter = false;
    private View broccoli;

   // private static final String[] ACTIVITY_RECOGNITION_PERMISSION = {Manifest.permission.ACTIVITY_RECOGNITION};

    private TextView mStepText;
//    private SensorManager mSensorManager;
//    private MySensorEventListener mListener;
//    public static int mStepDetector = 0;  // 自应用运行以来STEP_DETECTOR检测到的步数
//    public static int mStepCounter = 0;   // 自系统开机以来STEP_COUNTER检测到的步数


    long mTyReportStartTime = 0;
    long mTyReportEndTime = 0;

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_activity_link_webview;
    }


    public static final int REQUEST = 17;

    public static void setFromUserCenter(boolean isfromUser) {
        fromUserCenter = isfromUser;
    }

    /**
     * 打开一个网页
     *
     * @param title
     * @param url
     * @param context
     */
    public static void start(String title, String url, Activity context) {
        start(title, url, context, false, false);
    }

    public static void start(String title, String url, Activity context, boolean isTencentAct, boolean share) {
        Uri.Builder builder = new Uri.Builder();
        builder.appendQueryParameter("title", title);
        builder.appendQueryParameter("url", url);
        Intent intent = new Intent();
        ArticleItem articleItem = new ArticleItem();
        articleItem.setTitle(title);
        articleItem.setUrl(url);
        intent.putExtra("data", articleItem);
        intent.setData(builder.build());
        intent.putExtra("isTencentAct", isTencentAct);
        intent.putExtra("share", share);
        intent.setClass(context, WebViewPageActivity.class);
        context.startActivityForResult(intent, REQUEST);
    }

    public static void start(String title, String url, Long id, Activity context, boolean isTencentAct, boolean share) {
//        Uri.Builder builder = new Uri.Builder();
//        builder.appendQueryParameter("title", title);
//        builder.appendQueryParameter("url", url);
        Intent intent = new Intent();
        ArticleItem articleItem = new ArticleItem();
        articleItem.setTitle(title);
        articleItem.setUrl(url);
        articleItem.setId(id);
        intent.putExtra("data", articleItem);
//        intent.setData(builder.build());
        intent.putExtra("isTencentAct", isTencentAct);
        intent.putExtra("share", share);
        intent.setClass(context, WebViewPageActivity.class);
        context.startActivityForResult(intent, REQUEST);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
//        AndroidBug5497Workaround.assistActivity(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        broccoli = Utility.findViewById(mRootView, R.id.broccoli);
//        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            // 检查该权限是否已经获取
//            int get = ContextCompat.checkSelfPermission(this, ACTIVITY_RECOGNITION_PERMISSION[0]);
//            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
//            if (get != PackageManager.PERMISSION_GRANTED) {
//                // 如果没有授予该权限，就去提示用户请求自动开启权限
//                ActivityCompat.requestPermissions(this, ACTIVITY_RECOGNITION_PERMISSION, 321);
//            }
//            mListener = new MySensorEventListener();
//        }

        Uri uriData = getIntent().getData();
        fromUserCenter = getIntent().getBooleanExtra("fromUserCenter", false);
        if (uriData != null) {
            isFromH5OpenToReStart = UriTool.INSTANCE.isFromH5OpenToReStart(this, uriData);
            String articleid = uriData.getQueryParameter("articleid");
            String title = uriData.getQueryParameter("title");
            String cname = uriData.getQueryParameter("cname");
            String tag = uriData.getQueryParameter("tag");
            argUrl = uriData.getQueryParameter("url");
            try {
                String urlStr = uriData.toString();
                Log.w("APPTAG", "gettui:" + urlStr);
                String packName = getPackageName().replaceAll("\\.", "");
                String scheme = "gwa" + packName + "://browser?url=";
                if (urlStr.contains(scheme)) {
                    argUrl = URLDecoder.decode(urlStr.replace(scheme, ""));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            catalogItem = new CatalogItem();

            catalogItem.setCatname(cname);
            articleItem = new ArticleItem();
            try {
                articleItem.setTitle(title);
                if (!TextUtils.isEmpty(articleid))
                    articleItem.setId(Long.valueOf(articleid));
                if (!TextUtils.isEmpty(tag)) {
                    tokenTag = Integer.valueOf(tag);
                }
            } catch (Exception e) {
            }
        } else {
            Intent intent = getIntent();
            newsType = intent.getStringExtra("newsType");
            argUrl = intent.getStringExtra("url");
            tokenTag = intent.getIntExtra("tag", NeedTokenType.Delayed);
            catalogItem = intent.getParcelableExtra("catalog");
            articleItem = intent.getParcelableExtra("data");
            if (articleItem == null) {
                articleItem = ArticleItem.praseIntentDataToArticleItem(intent, TypeX.NEWS.LINK);
            }
        }
        catalogItem2 = catalogItem;
        linkType = getIntent().getIntExtra("LinkType", 0);
        isVrUrl = true;//代表是外链url
        super.onCreate(savedInstanceState);
        if (mRootView != null) {
            mRootView.setPadding(0, getStatusbar_height(), 0, 0);
        }
        if (argUrl!= null && argUrl.contains("tencentsurvey")){
            isTencentSurvey();
            return;
        }
        if (articleItem.getType() != TypeX.NEWS.TOPIC && articleItem.getType() != TypeX.CUSTOM.ACTIVITY && articleItem.getType() != TypeX.CUSTOM.ADVERT && articleItem.getType() != TypeX.NEWS.NEWS_PDF_MAGAZINE && articleItem.getId() > 0) {
            try {
                detialCallBack = new DetialCallBack();
                NewsDetailInvoker newsDetailInvoker = new NewsDetailInvoker(detialCallBack);
                String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
                newsDetailInvoker.getArticleById(articleItem.getId() + "", navigate_id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            initPage(argUrl);
            refreshBottomStyle(articleItem, 1);
        }
        checkNative(argUrl);
        initShare();
        initView();
//        setNewsTitle();//

        regisBrodCast();
        if (articleItem != null && !articleItem.isLinkNews() && articleItem.getFromComponent() != 1) {
            readStatus();
            getAppLinkUrlCustomParam(articleItem.getUrl());
        }
        showPageTransition();
        if (articleItem.getType() == 42 && UserInfo.isLogin(this)) {
            judgeInteval();
        }
    }

    /**
     * 针对腾讯问卷单独处理
     */
    private void isTencentSurvey() {
        if (UserInfo.isLogin(this)){
            getLoginCodeByOpenId();
        }else{
            showLoginDialog();
        }
    }

    public void getLoginCodeByOpenId(){
        MemberApi.getMemberApi()
                .getLoginCodeByOpenId(UserInfo.getUserInfo(this).getUserid())
                .compose(RxUtils.schedulersTransformer())
                .subscribe(new Observer<JSONObject>() {

                    @Override
                    public void onSubscribe(Disposable disposable) {

                    }

                    @Override
                    public void onNext(JSONObject jsonObject) {
                        if (isDestroyed() || isFinish) return;
                        if (jsonObject.optBoolean("success")){
                            JSONObject data = jsonObject.optJSONObject("data");
                            if (data!= null){
                                String code = data.optString("code");
                                String appId = "SOmHLwSg3IBY";
                                if (!TextUtils.isEmpty(data.optString("appId"))){
                                    appId = data.optString("appId") ;
                                }
                                String url = argUrl;
                                if (argUrl.endsWith("/")){
                                    url = argUrl.substring(0, argUrl.length() - 1);
                                }
                                String[] split = url.split("/");
                                String id = "";
                                String hash="";
                                if (split.length > 3){
                                    hash = split[split.length-1];
                                    id = split[split.length-2];
                                    url = split[0]+"//"+split[2]+"/api/v2/redirect";
                                }
                               // https://ahtv.tencentsurvey.net/api/v2/redirect?appid=SOmHLwSg3IBY&survey_id=10018&survey_hash=20d8&action=survey_collect&code=8b1ed6a3f507040e37c10525c165c04a7ef16843
                                if(url.contains("?")){
                                    url = url+"&"+"appid="+appId+"&survey_id="+id+"&survey_hash="+hash+"&code="+code+"&action=survey_collect";
                                }else {
                                    url = url + "?" + "appid=" + appId + "&survey_id=" + id + "&survey_hash=" + hash + "&code=" + code + "&action=survey_collect";
                                }
                                initPage(url);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void LoginListener(LoginEvent loginEvent) {
        if (UserInfo.isLogin(this)){
            getLoginCodeByOpenId();
        }else{
            showLoginDialog();
        }
    }

    private void showLoginDialog(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                IOSTips.showTips(WebViewPageActivity.this,
                        "该功能需要登录使用,请先登录",
                        "",
                        new IOSTips.Item2("取消", "#999999", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finish();
                            }
                        }),
                        new IOSTips.Item2("去登录", "#35C5CE", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LoginUtils.invokeLogin(WebViewPageActivity.this);
                            }
                        }));
            }
        },100);

    }


    IntegralConfig config;
    boolean openInteval = false;//是否开启积分任务
    int timeInteval = 0;//增加积分时间（分）
    int time = 0;//累计时长

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if (time <= timeInteval) {
                    time++;
                    handler.sendEmptyMessageDelayed(0, 1000);
                } else {
                    Addintegral.addintegral(WebViewPageActivity.this, 45, articleItem);
                }
            }
        }
    };

    //判断是否开启积分和无和成长任务
    private void judgeInteval() {
        config = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig;
        if (config != null) {
            if (config.enableList1 != null && config.enableList1.size() != 0) {
                for (int i = 0; i < config.enableList1.size(); i++) {
                    if (config.enableList1.get(i) == 45) {
                        openInteval = true;
                        timeInteval = config.book_least_duration_1;
                    }
                }
            }
        }
        String magazine_time = MMKV.defaultMMKV().getString("Magazine_Time" + UserInfo.getUserInfo(this).getUserid(), "");
        if (openInteval && !TextUtils.isEmpty(magazine_time)) {//判断有没有累计时间
            String[] s = magazine_time.split("_");
            time = Integer.parseInt(s[1]);
            if (s[0].equals(DateUtils.getDate())) {//是否是同一天
                if (time >= timeInteval) {//是否已添加过积分，已添加不走计时
                    return;
                }
            } else {
                time = 0;
                MMKV.defaultMMKV().remove("Magazine_Time" + UserInfo.getUserInfo(this).getUserid());
            }
        }
        if (openInteval && time < timeInteval) {
            handler.sendEmptyMessageDelayed(0, 1000);
        }
    }

    private void initView() {
//        try {
//            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mTitlebar_name.getLayoutParams();
//            lp.width = -1;
//            lp.addRule(RelativeLayout.END_OF,R.id.mTop_backContainer);
//            lp.addRule(RelativeLayout.START_OF,R.id.mTitlebar_MoreContainer);
//            mTitlebar_name.setLayoutParams(lp);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//        mTitlebar_name.setSingleLine(true);
//        mTitlebar_name.setEllipsize(TextUtils.TruncateAt.MARQUEE);
//        mTitlebar_name.setFocusable(true);
//        mTitlebar_name.setFocusableInTouchMode(true);
//        mTitlebar_name.requestFocus();


        //默认显示文稿title，原因：部分网页没有返回title。
        if (articleItem != null) {
            if (articleItem.getTitle() != null && !articleItem.getTitle().isEmpty()) {
                setTitle(articleItem.getTitle());
            } else if (articleItem.getReal_title() != null && !articleItem.getReal_title().isEmpty()) {
                setTitle(articleItem.getTitle());
            }
            if (articleItem.getShare_title() != null && !articleItem.getShare_title().isEmpty()) {
                setTitle(articleItem.getTitle());
            }
        }

        LinkedHashSet<String> linkedHashSet = getAppServerConfigInfo(this).getNewsDetailConfig().getLinkedHashSet();
        if (!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(NewsDetailStyleConfig.SHARE_BUTTON)) {
            hideMoreIcon();
        }

    }

    public void checkNative(String url) {
        Map<String, String> parms = WebViewUtils.getUrlParms(url);
        if (parms.containsKey("dyuserid") && parms.containsKey("appfactory_type") && parms.get("appfactory_type").equals("spider")) {
            MediaAuthorDetailActivity.start(this, parms.get("dyuserid"));
            finish();
        }
        if (parms.containsKey("linkType") && "earthMap".equals(parms.get("linkType"))) {
            isGlobal24 = true;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        collectionController.isVrUrl = true;

        collectionController.checkCollection();

//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                mSensorManager.registerListener(mListener, mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR),
//                        SensorManager.SENSOR_DELAY_NORMAL);
//                mSensorManager.registerListener(mListener, mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
//                        SensorManager.SENSOR_DELAY_NORMAL);
//            }
    }


    class DetialCallBack implements DataInvokeCallBack<ArticleItemReciver> {


        @Override
        public void success(ArticleItemReciver data) {
            if (data.state) {
                if (data != null && data.articleItem != null) {
                    if (articleItem != null && articleItem.getId() == data.articleItem.getId()) {
                        mTyReportEndTime = mTyReportStartTime = System.currentTimeMillis();
                    }
                    ReportKit.INSTANCE.escalationArticle(data.articleItem.getId()+"", data.articleItem.getTitle(),data.articleItem.getPublishdate(),data.articleItem.getAddUser());
                }
                UserRecommend.addItemKeyWord(data.articleItem, WebViewPageActivity.this);
                if (data.articleItem != null && URLUtil.isNetworkUrl(data.articleItem.getUrl())) {
                    if (articleItem.getType() == TypeX.NEWS.NEWS_PDF_MAGAZINE)
                        initPage(data.articleItem.getPdf_url());
                    else
                        initPage(data.articleItem.getUrl());
                } else {
                    initPage(argUrl);
                }
                if (data.articleItem != null && articleItem.getType() != TypeX.CUSTOM.ACTIVITY && articleItem.getType() != TypeX.NEWS.NEWS_PDF_MAGAZINE) {
                    //只管=于null  而且不是那种""  不要用isEmpty
                    if (data.articleItem.getTitle() != null)
                        articleItem.setTitle(data.articleItem.getTitle());
                    if (data.articleItem.getSummary() != null)
                        articleItem.setSummary(data.articleItem.getSummary());
                    if (articleItem.isLinkNews() && articleItem.getFromComponent() != 1)
                        setNewsTitle();
                    findViewById(R.id.linear_news_bottom_back_bar).setVisibility(View.VISIBLE);
                    mTitlebar_MoreContainer.setVisibility(View.GONE);
                    // showComment(data.articleItem);
                    refreshBottomStyle(data.articleItem, 1);
                }
                addReads(convertappfacSourceId(articleItem));
                AddMedalStatistics.addMedalStatistics(WebViewPageActivity.this); //勋章统计
                addIntegral();
            } else {
                initPage(argUrl);
            }
        }

        @Override
        public void fault(Object data) {
            initPage(argUrl);
        }
    }

    private String convertappfacSourceId(ArticleItem articleItem) {
        if (articleItem != null) {
            if (articleItem.getId() == 0 && !TextUtils.isEmpty(articleItem.getUrl())) {
                return MD5.md5(articleItem.getUrl());
            }
            return "" + articleItem.getId();
        }
        return "0";
    }

    private void addReads(final String article_id) {
        ReadStatusInvoker readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<BaseMessageReciver>() {
            @Override
            public void success(BaseMessageReciver data) {
                Log.w(TAG, "readStatusInvoker  " + "article_id  " + article_id + "success");
            }

            @Override
            public void fault(Object data) {
                Log.w(TAG, "readStatusInvoker  " + "article_id  " + article_id + "fault");
            }
        });
        readStatusInvoker.readStatistics(article_id, 1, 0);
    }

    private void regisBrodCast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WebViewFragment.ACTION);
        filter.addAction(WebViewFragment.TITLEACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, filter);

    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
//            int base=AppFactoryGlobalConfig.getAppServerConfigInfo(context).getBase();
            if (intent.getAction().equals(WebViewFragment.ACTION)) {
                boolean share = getIntent().getBooleanExtra("share", false);
                showShareWithConfig(share);
                setShareTitleUrl();
                //  clearShareItem(share);
                LinkedHashSet<String> linkedHashSet = getAppServerConfigInfo(WebViewPageActivity.this).getNewsDetailConfig().getLinkedHashSet();
                if (articleItem.getType() == 4){
                    if (articleItem.is_share == 1 ){
                        mTitlebar_MoreContainer.setVisibility(View.VISIBLE);
                    }else{
                        mTitlebar_MoreContainer.setVisibility(View.GONE);
                    }
                }else{
                    if(share && (linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) || linkedHashSet.contains(NewsDetailStyleConfig.SHARE_BUTTON))) {
                        mTitlebar_MoreContainer.setVisibility(View.VISIBLE);
                    }else {
                        mTitlebar_MoreContainer.setVisibility(View.GONE);
                    }
                }


            } else if (intent.getAction().equals(WebViewFragment.TITLEACTION)) {
                String title = intent.getStringExtra("title");
                if (catalogItem != null)
                    catalogItem.setCatname(title);
                if (articleItem != null && !articleItem.isCustomTitileFlag)
                    articleItem.setTitle(title);
                setTitle(title);
            }

        }

    };

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        if (time > 0) {
            MMKV.defaultMMKV().putString("Magazine_Time" + UserInfo.getUserInfo(this).getUserid(), DateUtils.getDate() + "_" + time);
        }
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
        super.onDestroy();
    }

    protected void setNewsTitle() {
        /*if (needLoadTopSecondBgSkin()) {
            return;
        }
        if (!TextUtils.isEmpty(getServerConfigTitle())) {
            setTitle(getServerConfigTitle());
        } else if (isNavigateTitle() && catalogItem != null) {
            setTitle(catalogItem.getCatname());
        } else if (articleItem != null) {
            setTitle(articleItem.getTitle());
        }*/

        int base = serverAppConfigInfo.getBase();
        if (base == TitileType.FRAME) {
//            setFrameTypeTitle();
        } else if (base == TitileType.NAVIGATE) {
            setTitle(catalogItem != null ? catalogItem.getCatname() : "");
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(articleItem != null ? (articleItem.getType() == 115 ? "积分商城" : articleItem.getTitle()) : "");
        } else if (base == TitileType.NOTITLE) {
            setTitle("");
        }
    }

    protected void addIntegral() {
        //不是真正的链接新闻 就不加积分
        if (articleItem == null || !articleItem.isLinkNews() || articleItem.getType() == TypeX.CUSTOM.ADVERT || "95599".equals(articleItem.getContent()))
            return;
        if (articleItem.getMovie() != null && articleItem.getMovie().getIsStudyContent() != null) {
            startAddIntegralCounter();
        }
    }

    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(WebViewPageActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0", articleItem);
            }
        });
    }

    @Override
    public void finish() {
        ReportKit.INSTANCE.escalationArticleTime();
        if (articleItem != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis();
            View anchor = findViewById(R.id.anchor_view);
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;
        try {
            if (fragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.remove(fragment);
                transaction.commitNowAllowingStateLoss();
            }
        } catch (Exception e) {

        } finally {
            super.finish();

        }
    }

    protected boolean needLoadTopSecondBgSkin() {
        //		return "1".equals(getResources().getString(R.string.need_load_second_topskin));
        return super.subClassgetNeedTopSecondBgSkin();
    }

    protected NavigateBarStyle getNewsDetailNavigateBarStyle() {
        if (articleItem != null && articleItem.getType() == TypeX.NEWS.TOPIC)
            return getAppServerConfigInfo(this).getTopicNewsBar();
        if (articleItem != null && !articleItem.isLinkNews())
            return null;
        return getAppServerConfigInfo(this).getLinkNewsBar();
    }

//    //后台关闭分享后只留收藏
//    private void clearShareItem(boolean share) {
//        if (!share && shareGridDataUtil != null) {
//            shareGridDataUtil.removeGridItem(ShareGridDataUtil.WeiXinFriend);
//            shareGridDataUtil.removeGridItem(ShareGridDataUtil.WeiXinCircle);
//            shareGridDataUtil.removeGridItem(ShareGridDataUtil.SinaWeiBo);
//            shareGridDataUtil.removeGridItem(ShareGridDataUtil.QQ);
//            shareGridDataUtil.removeGridItem(ShareGridDataUtil.QQZone);
//            shareGridDataUtil.removeGridItem(ShareGridDataUtil.CopyLink);
//        }
//    }

    private void initShare(){
        boolean share = getIntent().getBooleanExtra("share", false);
        showShareWithConfig(share);
        setShareTitleUrl();

        articleItem.isGlobal24 = isGlobal24;

        shareWrap.setShowFunction(true);
        shareWrap.init(articleItem, catalogItem);
    }


    public static class MyWebViewFragment extends WebViewFragment {
        boolean firstPage = true;
        WebViewPageActivity activity;
        boolean isLoadUrlRecive = false;

        public MyWebViewFragment() {
        }

        public String getUrl() {
            return mWebBrowser.getUrl();
        }

        public MyWebViewFragment setActivity(Activity activity) {
            if (activity instanceof WebViewPageActivity) {
                this.activity = (WebViewPageActivity) activity;
            }
            return this;
        }


        @Override
        public void onDestroy() {
            super.onDestroy();
            activity = null;
        }

        int count = 0;

        @Override
        protected void onSetTitle(String title) {
            super.onSetTitle(title);
            if (articleItem != null) {
                if (activity.getIntent().getStringExtra("title") == null || TextUtils.isEmpty(activity.getIntent().getStringExtra("title").trim())) {
                    articleItem.setTitle(title);
                    activity.setTitle(title);
                } else {
                    activity.setTitle(activity.getIntent().getStringExtra("title"));
                }
            }

            if (invokeShouldLoaderUrlTimes > 0) {
                if (!TextUtils.isEmpty(title)) {
                    activity.setTitle(title);
                }
            }


            if (invokeShouldLoaderUrlTimes < 2)
                return;

            if (articleItem != null && !TextUtils.isEmpty(title)
                    && !URLUtil.isNetworkUrl(title)
                    && title.toLowerCase().indexOf(".htm") == -1) {
                if (articleItem != null && TextUtils.isEmpty(activity.getIntent().getStringExtra("title"))) {
                    articleItem.setTitle(title);
                }
            }


            if (!isLoadUrlRecive)
                return;
            Log.w("APPTAG", "recive title:" + title);
            //不是真正的链接新闻
            // 并且 网页里面没取到过标题
            // 并且收到的网页标题不是空
            // 并且网页标题不是以http开头的
            // 也没检测到标题里面有啥子j8 .htm这种  那才通知变更标题
           /* if (getActivity() != null
                    && articleItem.getFromComponent() != 1
                    && (!articleItem.isLinkNews() ||articleItem.getType()==TypeX.News.TOPIC)
//                    && !articleItem.isCustomTitileFlag
                    && !TextUtils.isEmpty(title)
                    && !URLUtil.isNetworkUrl(title)
                    && title.toLowerCase().indexOf(".htm") == -1)*/
            boolean condition = isLoadUrlRecive && getActivity() != null
                    && articleItem.getType() != TypeX.NEWS.TOPIC
                    && !TextUtils.isEmpty(title)
                    && !URLUtil.isNetworkUrl(title)
                    && title.toLowerCase().indexOf(".htm") == -1;
            if ("APPTAG".equals(articleItem.getContent()) || condition) {
                Intent intent = new Intent(TITLEACTION);
                try {
                    intent.putExtra("title", URLDecoder.decode(title, "UTF-8"));
                    LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            isLoadUrlRecive = false;
        }

        @Override
        protected void initWebViewClient() {
            super.initWebViewClient();
            if (activity != null) {
                activity.topbackHandle = new TopbackHandle() {
                    @Override
                    public void handleBack() {
                        //用canGoBackOrForward代替canGoBack canGoBackOrForward(int steps)：以当前的页面为起始点，用来确认WebView的历史记录是否足以后退或前进给定的步数，正数为前进，负数为后退。(详细解释可以看上面的链接： https://www.jianshu.com/p/b8526e6b7760 )
                        if (mWebBrowser != null && mWebBrowser.canGoBackOrForward(-2)) {
                            mWebBrowser.goBack();
                        } else {
                            if (activity != null) {
                                activity.finish();
                            }
                        }
                    }
                };
                int value = activity.getIntent().getIntExtra(Intent.EXTRA_REFERRER, 0);
                if (value == 1) {
                    mWebBrowser.isFromImgTxtFrg = true;
                }
            }

            mWebBrowser.setWebViewClient(new WebBrowserX.WebClient(getActivity(), mWebBrowser) {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    // progressDialog.dismiss();
                    setLoadImageGone();
                    firstPage = false;
//                    if (mWebBrowser != null && mWebBrowser.canGoBack())
//                        activity.mTop_CloseContainer.setVisibility(View.VISIBLE);

                }

                @Override
                public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                    if (activity!=null){
                        WebResourceResponse webResourceResponse = OfflineWebUtil.INSTANCE.shouldInterceptRequest(activity, request);
                        if (webResourceResponse != null) {
                            return webResourceResponse;
                        }
                    }

                    return super.shouldInterceptRequest(view, request);
                }

                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Log.w(TAG, "shouldOverrideUrlLoading  :::::::: " + url);
                    WebBrowser.saveCookie(url, view.getContext());
                    if (checkWeiMeng(url, view)) {
                        return true;
                    }
                    activity.checkNative(url);
                    url = WebViewUtils.replaceDoubleQuesMark(url);
                    if (activity != null && articleItem != null && articleItem.getFromComponent() != 1) {
                        String urlOrg = "";
                        String urlCurrent = "";
                        try {
                            urlOrg = URLDecoder.decode(afterMgSignUrlOrgin, "UTF-8");
                        } catch (Exception e) {
                            e.printStackTrace();
                            try {
                                urlOrg = URLDecoder.decode(urlOrg.replaceAll("%", "%25"), "utf-8");
                            } catch (Exception e2) {
                                e2.printStackTrace();
                            }
                        }

                        try {
                            urlCurrent = URLDecoder.decode(afterMgSignUrlOrgin, "UTF-8");
                        } catch (Exception e) {
                            e.printStackTrace();
                            try {
                                urlCurrent = URLDecoder.decode(urlOrg.replaceAll("%", "%25"), "utf-8");
                            } catch (Exception e2) {
                                e2.printStackTrace();
                            }
                        }

//                        if (urlCurrent.equals(urlOrg) == false) {
                        activity.getAppLinkUrlCustomParam(url);
//                        }
                    }
                    if (!componentFirst && articleItem.getFromComponent() == 1) {
                        articleItem.setFromComponent(0);
                    }
                    componentFirst = false;
                    isComplete = false;
                    Map<String, String> param = WebViewUtils.getUrlParms(url);
                    String key = getResources().getString(R.string.logoUrl);//"logoUrl";//取爆料的分享页面
                    if (param != null && param.containsKey(key) && !TextUtils.isEmpty(param.get(key)) && activity != null && activity.articleItem != null)// && !activity.articleItem.isCustomTitileFlag)
                    {
                        activity.articleItem.setLogo(param.get(key));
                        if (activity.articleItem.getCustomColumns() != null)
                            activity.articleItem.getCustomColumns().setShare_logo(param.get(key));
                    }
//                    //调用拨号邮件等程序
//                    if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:") || url.startsWith("sms:")) {
//                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                        context.startActivity(intent);
//                        return true;
//                    } else//在导航页面中就打开
                    {
                        if (!WebViewLinkCMSNewsHandle.handleCMSNews(url, activity, articleItem, catalogItem2) && !SDKNewsItemJump.isMoreFunSDK(activity, url)) {
                            Log.w(TAG, "shouldOverrideUrlLoading not handle jump ");
                            /*if (!firstPage) {
                                activity.mTop_CloseContainer.setVisibility(View.VISIBLE);
                            }*/

                            if (URLUtil.isNetworkUrl(url)) {
                                firstPage = false;
                                Map<String, String> params = WebViewUtils.getUrlParms(url);
                                if (WebViewUtils.judgeDelayLoginParam(getActivity(), activity.tokenTag, params)) {
                                    if (WebViewUtils.judgeDelayLoginParamAndRefresh(getActivity(), activity.tokenTag, params)) {
                                        locationUrl = webBrowser.getUrl();
                                    }
                                    //locationUrl = url;//这暂时屏蔽掉 回来后还是用老地址 刷新一次就可以了 以后 回来的地址 可能会在参数里面取出来 赋值给locationUrl
                                    delayLoginTag = true;
                                    getLoginInfo();
                                    return true;
                                }
                                invokeShouldLoaderUrlTimes++;
                                isLoadUrlRecive = true;
                                loadUrl(view, url);
                            } else
                                matchDefaultUrl(url);
                        }else{
                            try {
                                ArticleItem itemData=new ArticleItem();
                                HttpUrl httpUrl=HttpUrl.parse(url);
                                Set<String> queryNames= httpUrl.queryParameterNames();
                                for (String str:queryNames){
                                    if ("preview".equals(str)){
                                        itemData.setPreview(httpUrl.queryParameter(str));
                                    }else if ("articleid".equals(str)){
                                        itemData.setId(Long.valueOf(httpUrl.queryParameter(str)));
                                    }else if ("linkType".equals(str)){
                                        itemData.isEPaper = "epaper".equals(httpUrl.queryParameter(str));
                                        itemData.isMagazine = "magazine".equals(httpUrl.queryParameter(str));
                                    }else if ("title".equals(str)){
                                        itemData.setTitle(httpUrl.queryParameter(str));
                                    }else if ("type".equals(str)){
                                        itemData.setType(Integer.parseInt(httpUrl.queryParameter(str)));
                                    }else if ("logo".equals(str)){
                                        itemData.setLogo(httpUrl.queryParameter(str));
                                    }
                                }
                                String tempUrl = url.replace(WebViewLinkCMSNewsHandle.ARG1, "");
                                tempUrl = tempUrl.replace(WebViewLinkCMSNewsHandle.ARG2, "");
                                itemData.setUrl(tempUrl);
                                itemData.setLinkNews(articleItem != null && articleItem.isLinkNews());
                                if (!HomeTab.isAtHome() && "首页".equals(TXReportManager.getInstance().getFirstTabInfo().getTabName()) ){
                                    TXReportManager.getInstance().app_jhapp_home_subtab_more_content_interact("点击查看详情",
                                            itemData,false);
                                }
                            }catch (Exception e){

                            }

                        }
                        Log.w(TAG, "shouldOverrideUrlLoading deal by application ");
                        return true;
                    }
                }
            });
        }
    }


    protected void initPage(String url) {
        fragment = new MyWebViewFragment().setActivity(this);
        fragment.isShowBroccoli = getIntent().getBooleanExtra("isShowBroccoli", true);
        Bundle args = new Bundle();
        articleItem.setUrl(url);
        args.putParcelable("data", articleItem);
        args.putString("url", url);//"http://wjtest.chinamcloud.com:8643/?TenantID=default");// "http://wjmorefun.chinamcloud.com/act/vote/index.html?act_id=5d5e4646-91e3-4697-9d1c-5f79215eb789"/*"http://special.jxntv.cn/ygj/"*/);
        args.putParcelable("catalog", catalogItem);
        args.putInt("tag", tokenTag);
        if (!TextUtils.isEmpty(newsType))
            args.putString("newsType", newsType);
        fragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.webFragment, fragment);
        transaction.show(fragment);
        transaction.commitNowAllowingStateLoss();
    }

    protected void getAppLinkUrlCustomParam(String url) {
        if (!TextUtils.isEmpty(url) && articleItem != null) {
            try {
                url = URLDecoder.decode(url, "utf-8");
            } catch (Exception e1) {
                e1.printStackTrace();
                try {
                    url = URLDecoder.decode(url.replaceAll("%", "%25"), "utf-8");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }


            String title = WebViewUtils.getAppShareTitle(url);
            if (WebViewUtils.conatinARG4(url)) {
                articleItem.isCustomTitileFlag = true;
                if (TextUtils.isEmpty(title)) {
                    title = " 	";//不要改这儿哈
                }
                articleItem.setTitle(title);
                /*Intent intent = new Intent(WebViewFragment.TITLEACTION);
                intent.putExtra("title", title);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);*/
            } else {
                articleItem.isCustomTitileFlag = false;
            }

            String app_share_summary = WebViewUtils.getAppShareSummary(url);
//            if(!TextUtils.isEmpty(app_share_summary))
//                articleItem.setSummary(app_share_summary);
//            else
//                articleItem.setSummary("");
            if (WebViewUtils.conatinARG5(url)) {
                if (TextUtils.isEmpty(app_share_summary)) {
                    app_share_summary = " 	";//不要改这儿哈
                }
                articleItem.setSummary(app_share_summary);
            } else
                articleItem.setSummary("");
            String app_share_logo = WebViewUtils.getAppShareLogo(url);
            if (WebViewUtils.conatinARG6(url)) {
                articleItem.setLogo(app_share_logo);
                if (articleItem.getCustomColumns() != null)
                    articleItem.getCustomColumns().setShare_logo(app_share_logo);
                if (!URLUtil.isNetworkUrl(app_share_logo)) {
                    articleItem.setLogo("");
                    if (articleItem.getCustomColumns() != null)
                        articleItem.getCustomColumns().setShare_logo("");
                }
            }
        }
    }

    interface TopbackHandle {
        void handleBack();
    }

    @Override
    protected void backHandle() {
        if (topbackHandle != null)
            topbackHandle.handleBack();
    }


    protected void setShareTitleUrl() {
        try {
            String url = argUrl;// ((MyWebViewFragment) fragment).getUrl();
            articleItem.setUrl(url);
        } catch (Exception e) {
        }
        if (linkType == TypeX.CUSTOM.ACTIVITY) {
            if (!TextUtils.isEmpty(articleItem.getShareTitle()))
                articleItem.setTitle(articleItem.getShareTitle());
            if (!TextUtils.isEmpty(articleItem.getShareImage()))
                articleItem.setLogo(articleItem.getShareImage());
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
    }

 /*   @Override
    protected String getContent_show_top_color() {
        if (articleItem != null && TypeX.Other.APPTAG.equals(articleItem.getContent()))
            return AppFactoryGlobalConfig.getAppServerConfigInfo(this).getTop_color();
        return super.getContent_show_top_color();
    }*/

    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        final boolean canInvoke = articleItem.getType() != TypeX.CUSTOM.ACTIVITY && articleItem.isLinkNews() && !"95599".equals(articleItem.getContent());
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                if (canInvoke)
                    AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                if (canInvoke)
                    AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            String id = articleItem.getId() == 0 ? "" : articleItem.getId() + "";

            AcquisitionManager.getInstance().readEnter(info, id,
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            String id = articleItem.getId() == 0 ? "" : articleItem.getId() + "";
            AcquisitionManager.getInstance().readExit(info, id,
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected boolean getFitSystemWindow() {
        return false;
    }

    @Override
    protected String getContent_show_top_color() {
        if (fromUserCenter) {
            mTitileBar.setBackgroundColor(Color.WHITE);
            return "#333333";
        } else {
            return super.getContent_show_top_color();
        }
    }

    @Override
    public int getStatusBarColor() {
        if (fromUserCenter)
            return Color.WHITE;
        else return super.getStatusBarColor();
    }


    @Override
    protected void onPause() {
        super.onPause();
//        mSensorManager.unregisterListener(mListener);
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == 321) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
//                    //提示用户手动开启权限
//                    new AlertDialog.Builder(this)
//                            .setTitle("健康运动权限")
//                            .setMessage("健康运动权限不可用")
//                            .setPositiveButton("立即开启", (dialog12, which) -> {
////
//                                // 跳转到应用设置界面
//                                Intent intent = new Intent();
//                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                                Uri uri = Uri.fromParts("package", getPackageName(), null);
//                                intent.setData(uri);
//                                startActivityForResult(intent, 123);
//                            })
//                            .setNegativeButton("取消", (dialog1, which) -> {
//                                com.utils.ToastUtil.showToastCenter(getApplicationContext(), "没有获得权限，应用无法运行！", Toast.LENGTH_SHORT).show();
//                                finish();
//                            }).setCancelable(false).show();
//                }
//            }
//        }
//    }
//
//    private  class MySensorEventListener implements SensorEventListener {
//        @Override
//        public void onSensorChanged(SensorEvent event) {
//
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                System.out.println("@@@:" + event.sensor.getType() + "--" + Sensor.TYPE_STEP_DETECTOR + "--" + Sensor.TYPE_STEP_COUNTER);
//
//                if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
//                    if (event.values[0] == 1.0f) {
//                        mStepDetector++;
//                    }
//                } else
//                if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
//                    mStepCounter = (int) event.values[0];
//                }
//
//                String desc = String.format(Locale.CHINESE, "设备检测到您当前走了%d步，自开机以来总数为%d步", mStepDetector, mStepCounter);
//            Log.e(TAG, "onSensorChanged: "+desc.toString());
////                mStepText.setText(desc);
//            }
//        }
//
//        @Override
//        public void onAccuracyChanged(Sensor sensor, int i) {
//
//        }
//    }
}